package com.zlei.code.threadTest;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author leizhang76
 * @Date 2021/2/2 14:47
 * 生产者
 */
public class Producer implements Runnable{

    private volatile boolean isRunning=true;
    //内存缓冲区
    private BlockingQueue<PCData> queue;
    //总数 原子操作
    private static AtomicInteger count=new AtomicInteger();
    private static final int SLEEPTIME=1000;

    public Producer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {

        PCData pcData=null;
        Random r = new Random();
        System.out.println("start producting id:"+Thread.currentThread().getId());
        try {
            while (isRunning){
                Thread.sleep(r.nextInt(SLEEPTIME));
                pcData=new PCData(count.incrementAndGet());
                System.out.println(pcData+"加入队列");
                if (!queue.offer(pcData,2, TimeUnit.SECONDS)){
                    System.out.println("加入队列失败");
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }

    }

    public void stop(){
        isRunning=false;
    }

}
